package com.jmb.api.web.service.impl;

import com.alibaba.druid.sql.visitor.functions.If;
import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jmb.api.common.exception.WebApiException;
import com.jmb.api.common.result.ResultCodeEnum;
import com.jmb.api.entity.Role;
import com.jmb.api.vo.role.RoleQueryVO;
import com.jmb.api.vo.role.RoleVO;
import com.jmb.api.web.mapper.PermissionMapper;
import com.jmb.api.web.mapper.PermissionRoleRefMapper;
import com.jmb.api.web.service.DbService;
import com.jmb.api.web.service.RoleService;
import com.jmb.api.web.mapper.RoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* @author 金梦博
* @description 针对表【t_role】的数据库操作Service实现
* @createDate 2025-09-25 17:20:51
*/

@Slf4j
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role>
    implements RoleService{
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionRoleRefMapper permissionRoleRefMapper;

    @Override
    public void saveOrUpdateRole(Role role) {
        // 判断是新增还是修改
        boolean isUpdate = role.getId() != null;
        log.info("isUpdate: " + isUpdate);
        
        // 检查角色名称是否已存在
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Role::getRoleName, role.getRoleName());
        
        // 如果是修改操作，需要排除当前角色本身
        if (isUpdate) {
            queryWrapper.ne(Role::getId, role.getId());
        }
        
        // 查询是否存在相同角色名称
        Role existingRole = roleMapper.selectOne(queryWrapper);
        if (existingRole != null) {
            // 角色已存在，抛出异常
            throw new WebApiException(ResultCodeEnum.web_ACCOUNT_EXIST_ERROR);
        }
        
        // 执行保存或更新操作
        super.saveOrUpdate(role);

    }

    @Override
    public IPage<Role> pageRoleByQuery(IPage<Role> roleVOPage, RoleQueryVO queryVO) {
        return roleMapper.pageRoleByQuery(roleVOPage, queryVO);
    }

    /**
     * 查询角色的权限permission_code
     * @param roleId 角色id
     * @return JSONArray JSON数组的对象，只有permission_code字段
     */
    @Override
    public JSONArray findPermissionCodeArrayByRoleId(Long roleId) {
        // 查询角色
        if (roleId == null){
            return new JSONArray();
        }
        List<String> list = roleMapper.selectPermissionCodeArrayByRoleId(roleId);
        return new JSONArray(list);
    }

}




